import React, { Component } from 'react'
import './selectItem.scss'
import {Option} from '../../types/vote'
import request from '../../util/request'
import {withRouter,RouteComponentProps} from 'react-router-dom'
import {connect} from 'react-redux'

//1.组件调用方式  路由直接调用   组件内部直接有路由相关的信息

//2.标签调用  路由相关信息：1》从父组件传递进来   2>高阶组件 withRouter

interface Iprops extends RouteComponentProps{
    option:Option,
    status:boolean,
    total:number,
    addVote:(id:number,vid:number,num:number) =>void
}

class selectItem extends Component<Iprops> {
    //投票的状态：是否投过票   占比的宽度计算
    render() {
        let {text,num} = this.props.option;
        let {status,total} = this.props;
        let width = num/total*100+'%';
        return (
            <div className="select-wrap" onClick={this.addVote}>
                <div className={status?"select-text":""} style={{position:'relative','zIndex':4}}>
                    <span className="text">{text}</span>
                    <span style={{display:status?'block':'none'}}>{num}</span>
                </div>
                <div className="poportion" style={{width:status?width:0}}></div>
            </div>
        )
    }

    //投票
    addVote = () => {
        //1.不能重复投票
        //vid:投票的id  id：选项的id
        if(!this.props.status){
            let {vid,id,num} = this.props.option;
            request.post('/api/vote',{vid,id}).then(res => {
                if(res.data.code === 1){
                    alert(res.data.msg);
                    //添加投票
                    this.props.addVote(id,vid,num)
                }
            })
        }else{
            alert("您已投过票")
        }
        
    }
}

let stateMapToProps = (state:any) => {
    return {}
}

let dispatchMapToProps = (dispatch:any) =>{
    return {
        addVote(id:number,vid:number,num:number){
            dispatch({type:'ADD_VOTE',id,vid,num})
        }
    }
}   

export default connect(stateMapToProps,dispatchMapToProps)(withRouter(selectItem))